package com.dream.myqiyi.home;
/**
 * @modify
 * ===>2013.8.2
 *     1.
 * **/

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.py.app.NiActivity;

import com.dream.myqiyi.R;
import com.dream.myqiyi.widget.FlowIndicator;

public class HomeActivity extends Activity {
	static final int SCROLL_ACTION = 0;
    private final int REFRESHLIST = 10;
	ExpandableListView mExpandableListView;
	Gallery mGallery;
	GalleryAdapter mGalleryAdapter;
	FlowIndicator mMyView;
	Timer mTimer;
	TextView zcfgtext1 ;
    private ExpandableAdapter adapter = null;

    private List<String> listGroup = null;
    private List<List<String>> listGroupData = null;
    
    private void initData() {

        List<String> child1 = new ArrayList<String>();
        List<String> child2 = new ArrayList<String>();
        List<String> child3 = new ArrayList<String>();
        List<String> child4 = new ArrayList<String>();
        List<String> child5 = new ArrayList<String>();

        child1 = getFiles("szdt");
        child2 = getFiles("zcfg");
        child3 = getFiles("tsjy");
        child4 = getFiles("tzgg");
        child5 = getFiles("qtnr");

        listGroupData.add(child1);
        listGroupData.add(child2);
        listGroupData.add(child3);
        listGroupData.add(child4);
        listGroupData.add(child5);


    }
    
    private List<String> getFiles(String str){
        AssetManager assetManager = getAssets();
        String[] files = null;
        try {
            files = assetManager.list(str);
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }
        List<String> child = new ArrayList<String>();
        if (files != null && files.length > 0){
            child.addAll(Arrays.asList(files));
        }
        return child;
    }
	
    //===>2013.8.2_1
    private static final String TAG="HomeActivity";
    private static final int LOGINSUC=0x0001;
    private Button loginbutton;
    //<==2013.8.2_1
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//<2013.8.2>
		setContentView(R.layout.home_activity);

        listGroup = new ArrayList<String>();
        listGroup.add(getResources().getString(R.string.szdt));
        listGroup.add(getResources().getString(R.string.zcfg));
        listGroup.add(getResources().getString(R.string.tsjy));
        listGroup.add(getResources().getString(R.string.tzgg));
        listGroup.add(getResources().getString(R.string.qtnr));

        listGroupData = new ArrayList<List<String>>();

		prepareView();

        new Thread(new Runnable() {
            @Override
            public void run() {
                initData();
                mHandler.sendEmptyMessage(REFRESHLIST);
            }
        }).start();

        loginbutton=(Button)findViewById(R.id.loginbutton);//<2013.8.2>
		mTimer = new Timer();
		mTimer.scheduleAtFixedRate(new MyTask(), 0, 5000);
		zcfgtext1 = (TextView)findViewById(R.id.zcfgtext);
	}

	private void prepareView() {
		mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView1);
		adapter = new ExpandableAdapter();
		View header = LayoutInflater.from(this).inflate(R.layout.header_view,
				null);
		mGallery = (Gallery) header.findViewById(R.id.home_gallery);
		mMyView = (FlowIndicator) header.findViewById(R.id.myView);
		mGalleryAdapter = new GalleryAdapter(this);
		mMyView.setCount(mGalleryAdapter.getCount());
		mGallery.setAdapter(mGalleryAdapter);
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				//
				mMyView.setSeletion(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		mExpandableListView.addHeaderView(header);
		mExpandableListView.setAdapter(adapter);
		
		mExpandableListView
                .setOnChildClickListener(new OnChildClickListener() {

                    @Override
                    public boolean onChildClick(ExpandableListView parent, View v,
                                                int groupPosition, int childPosition, long id) {
                        System.out.println("==" + groupPosition + "==" + childPosition);
                        Intent intent = new Intent();
                        intent.setClass(HomeActivity.this, TextActivity.class);
                        if (listGroup.get(groupPosition).equals(getResources().getString(R.string.szdt))){
                            intent.putExtra("group", "szdt");
                        } else if (listGroup.get(groupPosition).equals(getResources().getString(R.string.zcfg))){
                            intent.putExtra("group", "zcfg");
                        } else if (listGroup.get(groupPosition).equals(getResources().getString(R.string.tsjy))){
                            intent.putExtra("group", "tsjy");
                        }else if (listGroup.get(groupPosition).equals(getResources().getString(R.string.tzgg))){
                            intent.putExtra("group", "tzgg");
                        }else if (listGroup.get(groupPosition).equals(getResources().getString(R.string.qtnr))){
                            intent.putExtra("group", "qtnr");
                        }

                        intent.putExtra("child", listGroupData.get(groupPosition).get(childPosition));
                        startActivity(intent);
                        return false;
                    }
                });
	}
	

	private class MyTask extends TimerTask {
		@Override
		public void run() {
			mHandler.sendEmptyMessage(SCROLL_ACTION);
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case SCROLL_ACTION:
				// int curPos = mGallery.getSelectedItemPosition();
				// if (curPos < mGalleryAdapter.getCount() - 1) {
				// curPos++;
				// } else {
				// curPos = 0;
				// }
				// // mGallery.setLayoutAnimation(new LayoutAnimationController(
				// // AnimationUtils.loadAnimation(HomeActivity.this,
				// // R.anim.gallery_in)));
				// mGallery.setSelection(curPos, true);
				MotionEvent e1 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
						89.333336f, 265.33334f, 0);
				MotionEvent e2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
						SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
						300.0f, 238.00003f, 0);

				mGallery.onFling(e1, e2, -1300, 0);
				break;
            case  REFRESHLIST:
                adapter.notifyDataSetChanged();
                break;
			default:
				break;
			}
		}
	};

	
	private class ExpandableAdapter extends BaseExpandableListAdapter {
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return listGroupData.get(groupPosition).get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return 0;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            TextView myText = null;
            convertView = null;
            if (convertView != null) {
                myText = (TextView) convertView.findViewById(R.id.zcfgtext);
                String tempText = listGroupData.get(groupPosition).get(childPosition);
                if (tempText.indexOf(".") > 0){
                    myText.setText(tempText.substring(0,tempText.indexOf(".") - 1));
                } else {
                    myText.setText(tempText);
                }
            } else {
                convertView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.list_child_item1, null);
                myText = (TextView) convertView.findViewById(R.id.zcfgtext);
                String tempText = listGroupData.get(groupPosition).get(childPosition);
                String tempT = "";
                
                if (tempText.indexOf(".") > 0){
                	try{
                        InputStream is = getAssets().open("zcfg" + File.separator + tempText);
                        InputStreamReader inputStreamReader = new InputStreamReader(is,"gbk");
                        BufferedReader reader = new BufferedReader(inputStreamReader);
                        tempT = reader.readLine();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    myText.setText(tempT);
                } else {
                    myText.setText(tempText);
                }
            }
            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return listGroupData.get(groupPosition).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return listGroup.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return listGroup.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return 0;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            TextView myText = null;
            ImageView imageView = null;
            convertView = null;
            if (convertView != null) {
                myText = (TextView) convertView.findViewById(R.id.title_view);
                imageView = (ImageView) convertView.findViewById(R.id.tag_img);
                if (isExpanded) {
                    imageView.setImageResource(R.drawable.list_indecator_button_down);
                } else {
                    imageView.setImageResource(R.drawable.list_indecator_button);
                }

                myText.setText(listGroup.get(groupPosition));
            } else {
                convertView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.list_group_item, null);
                imageView = (ImageView) convertView.findViewById(R.id.tag_img);
                if (isExpanded) {
                    imageView.setImageResource(R.drawable.list_indecator_button_down);
                } else {
                    imageView.setImageResource(R.drawable.list_indecator_button);
                }
                myText = (TextView) convertView.findViewById(R.id.title_view);
                myText.setText(listGroup.get(groupPosition));
            }
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }
	//<2013.8.4>
	@Override
	protected void onResume() {
		Log.i(TAG, "onresume");
		if(NiActivity.SESSIONID!=null&&NiActivity.UNITNO!=null){
			loginbutton.setText(R.string.exit);
		    loginbutton.setTextColor(Color.RED);
		}else{
			loginbutton.setText(R.string.login2);
			loginbutton.setTextColor(getResources().getColor(R.color.aquamarine));
		}
		super.onResume();
	}


    /***
     * <2013.8.2>
     * ***/

   public void OnloginClick(View view){
       Log.i(TAG,"onloginClick method");
       if(NiActivity.SESSIONID==null||NiActivity.UNITNO==null){
           Intent loginintent=new Intent(HomeActivity.this, NiActivity.class);
           startActivityForResult(loginintent, 2);
       }else{
           AlertDialog.Builder ad=new AlertDialog.Builder(HomeActivity.this);
           ad.setIcon(android.R.drawable.ic_dialog_alert);
           ad.setMessage(R.string.weatherexit);
           ad.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   NiActivity.UNITNO = null;
                   NiActivity.SESSIONID = null;
                   Toast.makeText(HomeActivity.this, R.string.sucexit, Toast.LENGTH_SHORT).show();
                   loginbutton.setText(R.string.login2);
                   loginbutton.setTextColor(getResources().getColor(R.color.aquamarine));
               }
           });
           ad.setNegativeButton(R.string.cancel,null);
           ad.show();
       }

   }

    /***
     * <2013.8.2>
     * **/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case LOGINSUC:
                Toast.makeText(HomeActivity.this,R.string.login_suc,Toast.LENGTH_SHORT).show();
                loginbutton.setText(R.string.exit);
                loginbutton.setTextColor(Color.RED);
                break;
        }
    }
}
